package com.stylefeng.guns.crawlers.zgzc;

import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Response;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.modular.system.service.IDictService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wuchong
 */
@Crawler(name = "leagueCrawler")
public class LeagueNameCrawler extends BaseSeimiCrawler {

    private static final String MATCHER_PATTERN = "/soccer/([a-z]+?)/(\\d+?)";

    @Autowired
    private IDictService dictService;

    /**
     * @return 设置起始url
     */
    @Override
    public String[] startUrls() {
        return new String[]{"http://saishi.zgzcw.com/soccer"};
    }

    /**
     * 针对startUrl生成首批的response回调这个初始接口
     *
     * @param response --
     */
    @Override
    public void start(Response response) {

        JXDocument jxDocument = response.document();
        List<JXNode> jxNodeList = jxDocument.selN("//div[@class='ls']//div[@class='kuang']/a");
        List<Dict> dictList = jxNodeList.stream().map(jxNode -> {
            String href = jxNode.asElement().attr("href");
            Integer num = Integer.parseInt(StringUtils.substringAfterLast(href, "/"));
            String type = getType(href);
            Dict dict = null;
            if ("league".equals(type)) {
                String title = jxNode.asElement().getElementsByClass("lstitle").text();
                dict = new Dict();
                dict.setNum(num);
                dict.setName(title);
            }
            return dict;

        }).filter(Objects::nonNull).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(dictList)) {
            dictService.addDictItems("联赛", dictList.toArray(new Dict[0]));
        }
    }

    public String getType(String url) {
        Pattern pattern = Pattern.compile(MATCHER_PATTERN);
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }
}
